<script setup>
import store, {templateMapping} from "@/utils/store.js";
import MetaIcon from "@/components/MetaIcon.vue";
import MetaCode from "@/components/MetaCode.vue";
import {defaultData} from "@/utils/data.js";
import {renderTemplate} from "@/utils/tool.js";

const {data} = defineProps({
  data: {type: Object, default: defaultData},
})

const databases    = store.databases
const languages    = store.languages
const databaseData = store.templateDatabaseData
const languageData = store.templateLanguageData

const active = reactive({
  types: ['database', 'language'],
  type: 'database',
  item: 'postgres',
  code: 'CreateTable'
})

const renderResult  = computed(() => {
  const key = active.type + '-' + active.item + '-' + active.code
  const template = templateMapping.value.get(key)
  return renderTemplate(template, data)
})

function clickCode(type, code) {
  if (active.type !== type) {
    active.item = type === 'database' ? databases[0] : languages[0]
  }
  active.type = type
  active.code = code
}
</script>

<template>
  <div class="container">
    <div class="left">
      <el-collapse v-model="active.types">
        <el-collapse-item name="database">
          <template #title>
            <MetaIcon name="数据库" icon="database"/>
          </template>
          <div class="item" v-for="item in databaseData" @click="clickCode('database', item.code)" :class="active.type === 'database' && active.code === item.code ? 'active' : ''">{{item.name}}</div>
        </el-collapse-item>
        <el-collapse-item name="language">
          <template #title>
            <MetaIcon name="编程语言" icon="language"/>
          </template>
          <div class="item" v-for="item in languageData" @click="clickCode('language', item.code)" :class="active.type === 'language' && active.code === item.code ? 'active' : ''">{{item.name}}</div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="right">
      <el-tabs v-model="active.item">
        <el-tab-pane v-for="item in databases" :name="item" v-if="active.type === 'database'">
          <template #label>
            <MetaIcon :name="item"/>
          </template>
        </el-tab-pane>
        <el-tab-pane v-for="item in languages" :name="item" v-else>
          <template #label>
            <MetaIcon :name="item"/>
          </template>
        </el-tab-pane>

        <!-- 共享一个代码显示页面即可 -->
        <MetaCode :value="renderResult" :language="active.item"/>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  height: 100%;
  width: 100%;

  .left {
    width: 140px;
    flex-shrink: 0;

    .item {
      padding: 5px 0 5px 20px;
      cursor: pointer;
    }

    .active {
      background-color: var(--el-color-primary-light-5);
    }
  }

  .right {
    margin-left: 10px;
    flex-grow: 1;
    width: 0;

    .el-tabs {
      height: 100%;
    }
  }
}
</style>